import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/theme_provider.dart';
import '../providers/weather_provider.dart';
import '../constants/app_colors.dart';
import '../constants/app_themes.dart';
import '../constants/app_version.dart';
import '../screens/weather_animation_test_screen.dart';
import '../screens/weather_layout_test_screen.dart';
import '../screens/weather_alert_settings_screen.dart';
import '../screens/weather_alert_test_screen.dart';
import '../screens/all_location_test_screen.dart';
import '../screens/lunar_calendar_screen.dart';
import '../screens/weather_icons_test_screen.dart';
// import '../screens/radar_screen.dart'; // 已移除雷达图功能

/// 应用抽屉菜单
class AppDrawer extends StatelessWidget {
  const AppDrawer({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeProvider>(
      builder: (context, themeProvider, child) {
        return Drawer(
          backgroundColor: AppColors.backgroundPrimary,
          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              // 头部
              _buildDrawerHeader(context, themeProvider),

              // 基础功能组
              _buildSectionTitle('基础功能'),

              // 主题推荐提示
              _buildThemeRecommendation(context, themeProvider),

              // 主题配色快速切换
              _buildThemeQuickSwitch(context, themeProvider),

              const Divider(height: 16, indent: 16, endIndent: 16),

              // 主题设置
              _buildMenuItem(
                context,
                icon: themeProvider.isLightTheme
                    ? Icons.light_mode
                    : Icons.dark_mode,
                title: '主题设置',
                subtitle: _getThemeSubtitle(themeProvider),
                onTap: () {
                  Navigator.pop(context);
                  _showThemeDialog(context);
                },
              ),
              _buildMenuItem(
                context,
                icon: Icons.calendar_view_month_rounded,
                title: '黄历节日',
                subtitle: '查看农历、节气、宜忌',
                onTap: () {
                  Navigator.pop(context);
                  _navigateToLaoHuangLi(context);
                },
              ),
              _buildMenuItem(
                context,
                icon: Icons.notifications_active,
                title: '天气提醒设置',
                subtitle: '配置通勤时段和阈值',
                onTap: () {
                  Navigator.pop(context);
                  _navigateToWeatherAlertSettings(context);
                },
              ),

              // 天气雷达图功能已移除
              const Divider(height: 24, indent: 16, endIndent: 16),

              // 测试功能组（二级菜单，可展开/收起）
              _buildTestFunctionsMenu(context),

              const Divider(height: 24, indent: 16, endIndent: 16),

              // 关于应用
              _buildMenuItem(
                context,
                icon: Icons.info_outline,
                title: '关于应用',
                subtitle: 'v${AppVersion.version}',
                onTap: () {
                  Navigator.pop(context);
                  _showAboutDialog(context);
                },
              ),

              const SizedBox(height: 16),
            ],
          ),
        );
      },
    );
  }

  /// 构建抽屉头部
  Widget _buildDrawerHeader(BuildContext context, ThemeProvider themeProvider) {
    // 与 AppBar 和底部 tabbar 使用相同的背景颜色
    final headerDecoration = BoxDecoration(
      color: AppColors.backgroundSecondary,
    );

    // 使用主题色作为文字颜色（暗色模式下使用更亮的accent色）
    final textColor = themeProvider.isLightTheme
        ? AppColors.primaryBlue
        : AppColors.accentBlue; // 暗色模式使用更亮的强调色
    final subtextColor = AppColors.textTertiary; // 使用三级文字色（更淡）

    return DrawerHeader(
      decoration: headerDecoration,
      margin: EdgeInsets.zero,
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 应用图标（添加背景容器提高可见度）
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.asset(
                'assets/images/app_icon.png',
                width: 48,
                height: 48,
                fit: BoxFit.cover,
              ),
            ),
          ),
          const SizedBox(height: 12),
          // 应用名称
          Text(
            AppVersion.appName,
            style: TextStyle(
              color: textColor,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          // 应用描述
          Text(
            AppVersion.description,
            style: TextStyle(color: subtextColor, fontSize: 12),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  /// 构建主题推荐提示
  Widget _buildThemeRecommendation(
    BuildContext context,
    ThemeProvider themeProvider,
  ) {
    // 获取天气数据
    final weatherProvider = context.read<WeatherProvider>();
    final currentWeather = weatherProvider.currentWeather;
    String? weatherCode;

    if (currentWeather != null &&
        currentWeather.current?.current?.weatherPic != null) {
      weatherCode = currentWeather.current!.current!.weatherPic;
    }

    // 获取推荐主题
    final recommendation = themeProvider.getRecommendedTheme(
      weatherCode: weatherCode,
    );

    // 如果推荐的是当前主题，不显示提示
    if (recommendation['isCurrent'] == true) {
      return const SizedBox.shrink();
    }

    final recommendedScheme = recommendation['scheme'] as AppThemeScheme;
    final reason = recommendation['reason'] as String;

    return Container(
      margin: const EdgeInsets.fromLTRB(16, 8, 16, 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.backgroundSecondary.withOpacity(0.3),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: AppColors.primaryBlue.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.auto_awesome_outlined,
            color: AppColors.primaryBlue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  reason,
                  style: TextStyle(
                    color: AppColors.textPrimary,
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          FilledButton(
            onPressed: () {
              themeProvider.setThemeScheme(recommendedScheme);
              AppColors.setThemeProvider(themeProvider);
            },
            style: FilledButton.styleFrom(
              backgroundColor: AppColors.primaryBlue,
              foregroundColor: Colors.white,
              minimumSize: const Size(0, 32),
              padding: const EdgeInsets.symmetric(horizontal: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
            ),
            child: const Text(
              '应用',
              style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建主题配色快速切换
  Widget _buildThemeQuickSwitch(
    BuildContext context,
    ThemeProvider themeProvider,
  ) {
    final activeColor = themeProvider.isLightTheme
        ? AppColors.primaryBlue
        : AppColors.accentBlue;

    return Container(
      padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
      height: 90,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: AppThemes.allSchemes.asMap().entries.map((entry) {
          final index = entry.key;
          final scheme = entry.value;
          final isSelected =
              themeProvider.themeScheme == AppThemeScheme.values[index];

          return _ThemeCardWithPulse(
            width: 70,
            scheme: scheme,
            isSelected: isSelected,
            activeColor: activeColor,
            onTap: () {
              themeProvider.setThemeScheme(AppThemeScheme.values[index]);
              AppColors.setThemeProvider(themeProvider);
            },
          );
        }).toList(),
      ),
    );
  }

  /// 构建分组标题
  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
      child: Text(
        title,
        style: TextStyle(
          color: AppColors.textSecondary,
          fontSize: 12,
          fontWeight: FontWeight.w600,
          letterSpacing: 0.5,
        ),
      ),
    );
  }

  /// 构建测试功能二级菜单
  Widget _buildTestFunctionsMenu(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context, listen: false);
    // 暗色模式下使用更亮的强调色
    final iconColor = themeProvider.isLightTheme
        ? AppColors.primaryBlue
        : AppColors.accentBlue;

    return ExpansionTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: iconColor.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(Icons.science, color: iconColor, size: 22),
      ),
      title: Text(
        '测试功能',
        style: TextStyle(
          color: AppColors.textPrimary,
          fontSize: 15,
          fontWeight: FontWeight.w500,
        ),
      ),
      subtitle: Text(
        '开发调试工具',
        style: TextStyle(color: AppColors.textSecondary, fontSize: 12),
      ),
      iconColor: AppColors.textPrimary,
      collapsedIconColor: AppColors.textSecondary,
      children: [
        _buildSubMenuItem(
          context,
          icon: Icons.bug_report,
          title: '天气提醒测试',
          onTap: () {
            Navigator.pop(context);
            _navigateToWeatherAlertTest(context);
          },
        ),
        _buildSubMenuItem(
          context,
          icon: Icons.animation,
          title: '天气动画测试',
          onTap: () {
            Navigator.pop(context);
            _navigateToWeatherTest(context);
          },
        ),
        _buildSubMenuItem(
          context,
          icon: Icons.format_align_center,
          title: '天气布局测试',
          onTap: () {
            Navigator.pop(context);
            _navigateToWeatherLayoutTest(context);
          },
        ),
        _buildSubMenuItem(
          context,
          icon: Icons.location_on,
          title: '定位服务测试',
          onTap: () {
            Navigator.pop(context);
            _navigateToAllLocationTest(context);
          },
        ),
        _buildSubMenuItem(
          context,
          icon: Icons.image,
          title: '天气图标测试',
          onTap: () {
            Navigator.pop(context);
            _navigateToWeatherIconsTest(context);
          },
        ),
      ],
    );
  }

  /// 构建二级菜单项
  Widget _buildSubMenuItem(
    BuildContext context, {
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    final themeProvider = Provider.of<ThemeProvider>(context, listen: false);
    // 暗色模式下使用更亮的强调色
    final iconColor = themeProvider.isLightTheme
        ? AppColors.primaryBlue
        : AppColors.accentBlue;

    return ListTile(
      contentPadding: const EdgeInsets.only(left: 72, right: 16),
      leading: Icon(icon, color: iconColor, size: 20),
      title: Text(
        title,
        style: TextStyle(
          color: AppColors.textPrimary,
          fontSize: 14,
          fontWeight: FontWeight.w400,
        ),
      ),
      trailing: Icon(
        Icons.chevron_right,
        color: AppColors.textTertiary,
        size: 18,
      ),
      onTap: onTap,
    );
  }

  /// 构建菜单项
  Widget _buildMenuItem(
    BuildContext context, {
    required IconData icon,
    required String title,
    String? subtitle,
    required VoidCallback onTap,
  }) {
    final themeProvider = Provider.of<ThemeProvider>(context, listen: false);
    // 暗色模式下使用更亮的强调色
    final iconColor = themeProvider.isLightTheme
        ? AppColors.primaryBlue
        : AppColors.accentBlue;

    return ListTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: iconColor.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(icon, color: iconColor, size: 22),
      ),
      title: Text(
        title,
        style: TextStyle(
          color: AppColors.textPrimary,
          fontSize: 15,
          fontWeight: FontWeight.w500,
        ),
      ),
      subtitle: subtitle != null
          ? Text(
              subtitle,
              style: TextStyle(color: AppColors.textSecondary, fontSize: 12),
            )
          : null,
      trailing: Icon(
        Icons.chevron_right,
        color: AppColors.textTertiary,
        size: 20,
      ),
      onTap: onTap,
    );
  }

  /// 获取主题副标题
  String _getThemeSubtitle(ThemeProvider themeProvider) {
    switch (themeProvider.themeMode) {
      case AppThemeMode.light:
        return '亮色模式';
      case AppThemeMode.dark:
        return '暗色模式';
      case AppThemeMode.system:
        return '跟随系统';
    }
  }

  // ==================== 导航方法 ====================

  void _navigateToLaoHuangLi(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const LunarCalendarScreen(isSelectMode: false),
      ),
    );
  }

  void _navigateToWeatherTest(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const WeatherAnimationTestScreen(),
      ),
    );
  }

  void _navigateToWeatherLayoutTest(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const WeatherLayoutTestScreen()),
    );
  }

  void _navigateToAllLocationTest(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const AllLocationTestScreen()),
    );
  }

  void _navigateToWeatherIconsTest(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const WeatherIconsTestScreen()),
    );
  }

  void _navigateToWeatherAlertSettings(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const WeatherAlertSettingsScreen(),
      ),
    );
  }

  void _navigateToWeatherAlertTest(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const WeatherAlertTestScreen()),
    );
  }

  // 雷达图导航方法已移除

  // ==================== 对话框方法 ====================

  void _showThemeDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Consumer<ThemeProvider>(
          builder: (context, themeProvider, child) {
            AppColors.setThemeProvider(themeProvider);

            return AlertDialog(
              backgroundColor: AppColors.backgroundSecondary,
              surfaceTintColor: Colors.transparent,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              elevation: 3,
              title: Text(
                '主题设置',
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontSize: 24,
                  fontWeight: FontWeight.w500,
                ),
              ),
              contentPadding: const EdgeInsets.fromLTRB(24, 16, 24, 8),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 主题方案选择
                    Text(
                      '主题配色',
                      style: TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: AppThemes.allSchemes.asMap().entries.map((
                        entry,
                      ) {
                        final index = entry.key;
                        final scheme = entry.value;
                        final isSelected =
                            themeProvider.themeScheme ==
                            AppThemeScheme.values[index];

                        final activeColor = themeProvider.isLightTheme
                            ? AppColors.primaryBlue
                            : AppColors.accentBlue;

                        return GestureDetector(
                          onTap: () {
                            themeProvider.setThemeScheme(
                              AppThemeScheme.values[index],
                            );
                            AppColors.setThemeProvider(themeProvider);
                          },
                          child: Container(
                            width: 70,
                            height: 70,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(12),
                              // 选中时添加明显的边框和阴影
                              border: Border.all(
                                color: isSelected
                                    ? activeColor
                                    : Colors.transparent,
                                width: isSelected ? 3 : 0,
                              ),
                              boxShadow: isSelected
                                  ? [
                                      BoxShadow(
                                        color: activeColor.withOpacity(0.3),
                                        blurRadius: 8,
                                        spreadRadius: 2,
                                      ),
                                    ]
                                  : null,
                            ),
                            child: Container(
                              decoration: BoxDecoration(
                                color: scheme.previewColor,
                                borderRadius: BorderRadius.circular(9),
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    scheme.icon,
                                    color: Colors.white,
                                    size: 24,
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    scheme.name.replaceAll('主题', ''),
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 11,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                    const SizedBox(height: 24),
                    // 亮暗模式选择
                    Text(
                      '显示模式',
                      style: TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    _buildThemeOption(
                      context,
                      '亮色主题',
                      AppThemeMode.light,
                      Icons.light_mode,
                      themeProvider.themeMode == AppThemeMode.light,
                    ),
                    const SizedBox(height: 8),
                    _buildThemeOption(
                      context,
                      '暗色主题',
                      AppThemeMode.dark,
                      Icons.dark_mode,
                      themeProvider.themeMode == AppThemeMode.dark,
                    ),
                    const SizedBox(height: 8),
                    _buildThemeOption(
                      context,
                      '跟随系统',
                      AppThemeMode.system,
                      Icons.settings_brightness,
                      themeProvider.themeMode == AppThemeMode.system,
                    ),
                  ],
                ),
              ),
              actionsPadding: const EdgeInsets.fromLTRB(24, 0, 24, 16),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  style: TextButton.styleFrom(
                    foregroundColor: themeProvider.isLightTheme
                        ? AppColors.primaryBlue
                        : AppColors.accentBlue, // 暗色模式使用更亮的强调色
                    padding: const EdgeInsets.symmetric(
                      horizontal: 24,
                      vertical: 10,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text('确定'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildThemeOption(
    BuildContext context,
    String title,
    AppThemeMode mode,
    IconData icon,
    bool isSelected,
  ) {
    return Consumer<ThemeProvider>(
      builder: (context, themeProvider, child) {
        AppColors.setThemeProvider(themeProvider);

        // 暗色模式下使用更亮的强调色
        final activeColor = themeProvider.isLightTheme
            ? AppColors.primaryBlue
            : AppColors.accentBlue;

        return Container(
          margin: const EdgeInsets.symmetric(vertical: 2),
          decoration: BoxDecoration(
            color: isSelected
                ? activeColor.withOpacity(
                    themeProvider.isLightTheme ? 0.15 : 0.24,
                  )
                : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
            border: isSelected
                ? Border.all(color: activeColor, width: 2)
                : Border.all(
                    color: AppColors.borderColor.withOpacity(0.3),
                    width: 1,
                  ),
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 4,
            ),
            leading: Icon(
              icon,
              color: isSelected ? activeColor : AppColors.textSecondary,
              size: 24,
            ),
            title: Text(
              title,
              style: TextStyle(
                color: isSelected ? activeColor : AppColors.textPrimary,
                fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                fontSize: 16,
              ),
            ),
            trailing: isSelected
                ? Icon(Icons.check_circle, color: activeColor, size: 24)
                : const SizedBox(width: 24),
            onTap: () {
              themeProvider.setThemeMode(mode);
              AppColors.setThemeProvider(themeProvider);
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }

  void _showAboutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: AppColors.backgroundSecondary,
          surfaceTintColor: Colors.transparent,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          elevation: 3,
          icon: Icon(
            Icons.info_outline_rounded,
            color: AppColors.primaryBlue,
            size: 32,
          ),
          title: Text(
            '关于应用',
            style: TextStyle(
              color: AppColors.textPrimary,
              fontSize: 24,
              fontWeight: FontWeight.w500,
            ),
          ),
          contentPadding: const EdgeInsets.fromLTRB(24, 0, 24, 8),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                AppVersion.appName,
                style: TextStyle(
                  color: AppColors.textPrimary,
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                '版本: ${AppVersion.version} (构建 ${AppVersion.buildNumber})',
                style: TextStyle(
                  color: AppColors.textSecondary,
                  fontSize: 14,
                  height: 1.5,
                ),
              ),
              const SizedBox(height: 6),
              Text(
                AppVersion.description,
                style: TextStyle(
                  color: AppColors.textSecondary,
                  fontSize: 14,
                  height: 1.5,
                ),
              ),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: AppColors.primaryBlue.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '🎉 v${AppVersion.version} 更新内容',
                      style: TextStyle(
                        color: AppColors.primaryBlue,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '• 黄历详情页面改为滑动页面设计\n'
                      '• 新增AI解读页面，支持左右滑动切换\n'
                      '• 优化通勤提醒自动清理逻辑\n'
                      '• 修复通勤提醒时段结束后不消失的问题\n'
                      '• 优化日出日落卡片布局，更加紧凑\n'
                      '• 修复页面指示器按钮颜色显示问题',
                      style: TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 12,
                        height: 1.6,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              Text(
                AppVersion.copyright,
                style: TextStyle(color: AppColors.textTertiary, fontSize: 12),
              ),
            ],
          ),
          actionsPadding: const EdgeInsets.fromLTRB(24, 0, 24, 16),
          actions: [
            FilledButton(
              onPressed: () => Navigator.of(context).pop(),
              style: FilledButton.styleFrom(
                backgroundColor: AppColors.primaryBlue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 10,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }
}

/// 带脉冲动画的主题卡片
class _ThemeCardWithPulse extends StatefulWidget {
  final double width;
  final ThemeColorScheme scheme;
  final bool isSelected;
  final Color activeColor;
  final VoidCallback onTap;

  const _ThemeCardWithPulse({
    required this.width,
    required this.scheme,
    required this.isSelected,
    required this.activeColor,
    required this.onTap,
  });

  @override
  State<_ThemeCardWithPulse> createState() => _ThemeCardWithPulseState();
}

class _ThemeCardWithPulseState extends State<_ThemeCardWithPulse>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnimation;
  late Animation<double> _glowAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    )..repeat(reverse: true);

    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.05,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));

    _glowAnimation = Tween<double>(
      begin: 0.3,
      end: 0.6,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));

    // 只在选中时播放动画
    if (widget.isSelected) {
      _controller.forward();
    }
  }

  @override
  void didUpdateWidget(_ThemeCardWithPulse oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当选中状态改变时，控制动画
    if (widget.isSelected && !oldWidget.isSelected) {
      _controller.forward();
    } else if (!widget.isSelected && oldWidget.isSelected) {
      _controller.reset();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      margin: const EdgeInsets.only(right: 12),
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedBuilder(
          animation: _controller,
          builder: (context, child) {
            return Transform.scale(
              scale: widget.isSelected ? _scaleAnimation.value : 1.0,
              child: child,
            );
          },
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: widget.isSelected
                    ? widget.activeColor
                    : Colors.transparent,
                width: widget.isSelected ? 3 : 0,
              ),
              boxShadow: widget.isSelected
                  ? [
                      // 内层阴影（边框高光）
                      BoxShadow(
                        color: widget.activeColor.withOpacity(0.5),
                        blurRadius: 0,
                        spreadRadius: 1,
                      ),
                      // 中层阴影（光晕效果）
                      BoxShadow(
                        color: widget.activeColor.withOpacity(
                          _glowAnimation.value,
                        ),
                        blurRadius: 16,
                        spreadRadius: 3,
                      ),
                      // 外层阴影（柔和效果）
                      BoxShadow(
                        color: widget.activeColor.withOpacity(0.3),
                        blurRadius: 12,
                        spreadRadius: 2,
                      ),
                    ]
                  : null,
            ),
            child: Container(
              decoration: BoxDecoration(
                color: widget.scheme.previewColor,
                borderRadius: BorderRadius.circular(9),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(widget.scheme.icon, color: Colors.white, size: 24),
                  const SizedBox(height: 4),
                  Text(
                    widget.scheme.name.replaceAll('主题', ''),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 11,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
